package com.gj.demojuc.chap05;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 * 6辆车抢占3个车位
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //permits资源数量
        Semaphore semaphore = new Semaphore(3);//默认不公平

        //6辆车
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//申请资源 阻塞方法
                    System.out.println(Thread.currentThread().getName() + "申请到了一个停车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(10));//停车时间
                    System.out.println(Thread.currentThread().getName() + "离开");
                    semaphore.release();//释放资源
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },"车辆" + i).start();
        }
    }
}
